import React, { Suspense } from 'react';
import { Card, Col, Divider, Layout, message, Modal, Row, Spin, Tooltip, Tree,Icon } from 'antd';
import styles from '../answerLibrary.css';
import jin from '@/assets/overview/jin.png';
import icon4 from '@/assets/overview/4.png';
import icon6 from '@/assets/overview/6.png';
import icon7 from '@/assets/overview/7.png';
import chu from '@/assets/overview/chu.png';

import { getAnswerTree, answerNodeDelete } from '@/services/knowledgemanagement';
import AddOrEditNode from '@/pages/KnowledgeManagement/AnswerLibrary/leftTree/addOrEditNode';

class LeftTree extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isOperation: false,
      treeData: [],
      loading: true,
      expandedKeys: [],
      selectedKeys: [],
      currentNode: {},
      visible: false,
      autoExpandParent: true,
      modalType: 'add'
    }
  }

  componentDidMount() {
    this.getTreeList('start')
  }

  /**
   * 显隐操作按钮
   */
  isShowOperation = () => {
    const { isOperation } = this.state;
    this.setState({ isOperation: !isOperation });
  }

  /**
   * 获取树list
   * @returns {*}
   */
  getTreeList = (flag) => {
    this.setState({ loading: true }, async () => {
      const res = await getAnswerTree();
      if (res && res[0]) {
        //判断展开收起状态 若有存储的展开节点 则取存储的节点 若没有 则默认展开所有分类
        const childrenIds = [res[0].id];
        this.localStorageKeys(childrenIds);
        this.setState({ treeData: res ? res : [], loading: false }, () => {
          if (flag && flag === 'start') {
            //初始化默认选中所有分类
            const item = res[0];
            this.initTreeSelect(item);
          }
        })
      } else {
        this.setState({ loading: false })
      }
    })
  }

  /**
   * 初始化默认选中所有分类
   */
  initTreeSelect = (item) => {
    const info = {
      disabled: item.disabled,
      id: item.id,
      name: item.name,
      parentId: item.parentId,
      parentPath: item.parentPath,
      weight: item.weight
    };
    this.setState({ selectedKeys: [item.id], currentNode: info }, () => {
      this.props.sendNodeToRightList(info)
    })
  }

  /**
   * 处理记忆展开收起状态
   * @param keys
   */
  localStorageKeys = (keys) => {
    //先判断有没有储存的展开收起 如果没有则展开所有分类节点，如果有，则展开储存的节点
    const answerTreeExpandedKeys = window.localStorage.getItem('answerTreeExpandedKeys');
    if (answerTreeExpandedKeys) {
      this.setState({ expandedKeys: answerTreeExpandedKeys.split(',') })
    } else {
      window.localStorage.setItem('answerTreeExpandedKeys', keys);
      this.setState({ expandedKeys: keys })
    }
  }

  /**
   * 加载树节点
   * @returns {*}
   */
  renderTreeNodes = data => {
    const { expandedKeys,selectedKeys } = this.state;
    const selected = selectedKeys[0] ? selectedKeys[0] : ''
    return data.map(item => {
      const info = {
        disabled: item.disabled,
        id: item.id,
        name: item.name,
        parentId: item.parentId,
        parentPath: item.parentPath,
        weight: item.weight
      };
      if (item.children) {
        return (
          <Tree.TreeNode title={item.name} key={item.id} info={info}
          icon={expandedKeys.indexOf(item.id) === -1 ? 
            <img src={staticPath+"/sysKnowledge/unfold.png"} />
              : 
            <img src={staticPath+"/sysKnowledge/fold.png"} />
          }
        >
            {this.renderTreeNodes(item.children)}
          </Tree.TreeNode>
        )
      } else {
        return (
          <Tree.TreeNode title={item.name} key={item.id} info={info} 
          icon={<img src={staticPath+"/sysKnowledge/leaf.png"} />}
          switcherIcon={<Icon type="minus-square" />} />
        )
      }
    })
  }

  /**
   * 树的展开和收起
   */
  doExpand = (expandedKeys) => {
    this.setState({ expandedKeys, autoExpandParent: false });
  }

  /**
   * 选中树
   * @returns {*}
   */
  onSelectTree = (selectedKeys, nodeInfo) => {
    //不使用selectedKeys为是否选中 因为当选中状态再次点击时，selectedKeys为[]，选中状态取消；直接使用nodeInfo，使节点一直处于被选中状态
    const info = nodeInfo.node.props.info;
    //如果该节点下有子菜单，则触发点击菜单展开收起的方法
    const nodeChildren = nodeInfo.node.getNodeChildren();
    if (nodeChildren.length > 0) {
      this.onClickToCollapse(info.id);
    };
    this.setState({ selectedKeys: [info.id], currentNode: info }, () => {
      this.props.sendNodeToRightList(info);
    })
  }

  /**
   * 触发点击菜单展开收起的方法
   */
  onClickToCollapse = (id) => {
    let { expandedKeys } = this.state;
    let expandedKeysNew = [];
    if (expandedKeys.indexOf(id) === -1) {
      expandedKeys.push(id);
      expandedKeysNew = expandedKeys;
    } else {
      const index = expandedKeys.indexOf(id);
      expandedKeysNew = expandedKeys.filter((item, i) => i != index);
    };
    this.doExpand(expandedKeysNew);
  }

  /**
   * 删除分类
   * @returns {*}
   */
  deleteCategory = () => {
    const { currentNode } = this.state;
    Modal.confirm({
      title: '确定要删除该分类吗？',
      okText: '确定',
      cancelText: '取消',
      okType: 'danger',
      onOk: async () => {
        const res = await answerNodeDelete({ parentPath: currentNode.parentPath, id: currentNode.id })
        //成功删除分类之后 需要刷新分类树并且初始化默认选中所有分类
        this.getTreeList('start')
        message.info(res.message)
      }
    })
  }

  /**
   * 打开 新增/修改 的弹窗
   * @returns {*}
   */
  openModal = (modalType) => {
    this.setState({ visible: true, modalType })
  }

  /**
   * 关闭 新增/修改 的弹窗
   * @returns {*}
   */
  cancelModal = () => {
    this.setState({ visible: false })
  }

  /**
   * 新增或修改成功后关闭弹窗并刷新树
   * @returns {*}
   */
  refreshTreeList = (name) => {
    let { currentNode } = this.state;
    currentNode.name = name ? name : currentNode.name;
    this.setState({ ...currentNode, }, () => {
      this.cancelModal();
      this.getTreeList();
    })
  }

  render() {
    const { isOperation, loading, treeData, expandedKeys, selectedKeys, currentNode, visible, modalType, autoExpandParent } = this.state;
    //若当前节点为所有分类 是则删除和修改按钮不允许操作
    const isRoot = currentNode && currentNode.parentId && currentNode.parentId === '0';
    //若当前没有选中的节点 则删除和修改按钮不允许操作
    const isCurrentNode = !currentNode || !currentNode.id || !currentNode.parentId;
    return (
      <div>
        <Spin spinning={loading}>
          {
            isOperation ? (
              <div className="'clearfix'" style={{ height: 25, width: '100%',padding:"0 10px" }}>
                <div className={styles.operationBox}>
                  <Tooltip placement="top" title="删除分类" arrowPointAtCenter>
                    <img
                      src={icon4}
                      className={styles.iconsNew}
                      style={{ pointerEvents: isRoot || isCurrentNode ? 'none' : '', opacity: isRoot || isCurrentNode ? '0.5' : '1' }}
                      onClick={this.deleteCategory}
                    />
                  </Tooltip>
                  <Tooltip placement="top" title="修改名称" arrowPointAtCenter>
                    <img
                      className={styles.iconsNew}
                      src={icon6}
                      style={{ pointerEvents: isRoot || isCurrentNode ? 'none' : '', opacity: isRoot || isCurrentNode ? '0.5' : '1' }}
                      onClick={() => this.openModal('edit')}
                    />
                  </Tooltip>
                  <Tooltip placement="top" title="添加分类" arrowPointAtCenter>
                    <img
                      className={styles.iconsNew}
                      src={icon7}
                      // style={{pointerEvents:isCurrentNode ? 'none' : '',opacity:isCurrentNode ? '0.5' : '1'}}
                      onClick={() => this.openModal('add')}
                    />
                  </Tooltip>
                </div>
                <div className={styles.back}>
                  <Tooltip placement="top" title="返回" arrowPointAtCenter>
                    <img
                      className={styles.iconsNew}
                      src={chu}
                      onClick={this.isShowOperation}
                    />
                  </Tooltip>
                </div>

              </div>
            ) : (
              <div className="'clearfix'" style={{ height: 25, width: '100%',padding:"0 10px"  }}>
                <div className={styles.treeTitle}>分类</div>
                <div className={styles.openIcon}>
                  <img src={jin} style={{ cursor: 'pointer' }} onClick={this.isShowOperation} />
                </div>
              </div>
            )
          }
          <Divider style={{ margin: '12px 0' }} />
          <div style={{padding:"0 10px" }}>
            <Tree
              onSelect={this.onSelectTree}
              showIcon={true}
              expandedKeys={expandedKeys}
              onExpand={this.doExpand}
              autoExpandParent={autoExpandParent}
              selectedKeys={selectedKeys}
              showLine={true}
            >
              {this.renderTreeNodes(treeData)}
            </Tree>
          </div>
          <AddOrEditNode
            visible={visible}
            currentNode={currentNode}
            cancelModal={this.cancelModal}
            modalType={modalType}
            refreshTreeList={this.refreshTreeList}
          />
        </Spin>

      </div>
    );
  }
}

export default LeftTree;
